package com.my.hotel.controller.serverPage;

import com.alipay.api.internal.util.AlipaySignature;

import com.my.hotel.entity.Order;
import com.my.hotel.entity.serverPage.JdUser;
import com.my.hotel.entity.vo.Trade;
import com.my.hotel.mapper.ArticleMapper;
import com.my.hotel.mapper.OrderMapper;
import com.my.hotel.service.ArticleService;
import com.my.hotel.service.JdUserService;
import com.my.hotel.service.OrderService;
import com.my.hotel.service.PayService;
import com.my.hotel.util.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@Controller

public class PayController {

    @Autowired
    private PayService payService;

    @PostMapping("/utils/pay")
    public void pay(HttpServletRequest req,Trade trade, HttpServletResponse response) throws Exception{

        HttpSession session = req.getSession();
        session.removeAttribute("preOrder");
        session.setAttribute("preOrder",trade);
        //产生交易订单号，不能重复
        trade.setTradeNo(UUID.randomUUID().toString());


        try {
            payService.addOrder(trade,"4",session);
        } catch (ParseException e) {
            e.printStackTrace();
        }



        //支付
        payService.pay(trade,response);


    }

    @RequestMapping("/utils/success")
    public String success(HttpServletRequest request) throws Exception{

        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            return "forward:/utils/clear/"+out_trade_no;
        }
        return "";
    }

    /**
     * 订单付款成功后，清除该订单的购物信息
     */

@Autowired
    OrderMapper orderMapper;
@Autowired
    JdUserService jdUserService;
    @GetMapping("/utils/clear/{tradeNo}")
    public String clearCart(HttpServletRequest request,@PathVariable("tradeNo") String tradeNo){
        payService.update(tradeNo);
        Order order = orderMapper.getOneByTradeNo(tradeNo);
        int userId = order.getUserId();
        JdUser clientById = jdUserService.getClientById(userId);
        request.getSession().setAttribute("userInfo",clientById);
        System.out.println("订单:"+tradeNo+"已付款！清除对应的信息");
        //登录成功的跳转界面
        return "forward:/utils/forward/index/5";
    }










}
